<?php

require_once "data/dao/FriendCodeDAO.php";
require_once "services/FacebookProxy.php";
require_once "data/dao/UserDAO.php";

class CodeHandler{
	
	private $user;
	
	public function CodeHandler(){
		
		$facebook = new FacebookProxy();
		$this->user = $facebook->getLoggedInUser();
		
		if($_REQUEST['do'] == "add-friend-code"){
			$this->addFriendCode($this->user, $_REQUEST['game-id'], 
				$_REQUEST['friend-code-value']);
		}
		if($_REQUEST['do'] == "add-wii-code"){
			$this->addWiiCode($this->user, $_REQUEST['wii-code-value']);
		}
		if($_REQUEST['do'] == "delete-wii-code"){
			$this->deleteWiiCode($this->user);
		}
	}
	
	private function addWiiCode($userId, $wiiCode){
		
		$udao = new UserDAO();
		
		try{
			$udao->addWiiCode($userId, $wiiCode);
		}
		catch(Exception $e){
			
			$message = urlencode("Invalid Wii Code, must be 16 digit code" .
					" in any of the following formats: 0000000000000000, " .
					"0000-0000-0000-0000");
			// problem with wii code, show error message
			header("Location: index.php?error=".$message);
			return;
		}
		$facebook = new FacebookProxy();
		$facebook->updateProfile();
		header("Location: index.php");
	}
	
	private function deleteWiiCode($userId){
		
		$udao = new UserDAO();
		$udao->deleteWiiCode($userId);
		
		$facebook = new FacebookProxy();
		$facebook->updateProfile();
		header("Location: index.php");		
	}
	
	private function addFriendCode($userID, $gameID, $friendCode){
					
		$fcdao = new FriendCodeDAO();
		
		try{
			$fcdao->addFriendCode($userID, $gameID, $friendCode);
			$facebook = new FacebookProxy();
			$facebook->updateProfile();
		}
		catch(Exception $e){

			$message = urlencode("Invalid Friend Code, must be 12 digit code" .
					" in any of the following formats: 000000000000, " .
					"0000-0000-0000, or an EA Nation code for supported games." );
			header("Location: index.php?error=" . $message);
			return;
		}
		header("Location: index.php");
	}
}
$ch = new CodeHandler();
?>
